//
//  MessageRootController.m
//  collection
//
//  Created by 靖 张 on 12/14/11.
//  Copyright (c) 2011 Tsinghua University. All rights reserved.
//

#import "MessageRootController.h"
#import "CollectionDataManager.h"
#import "MentionedMessageController.h"
#import "PrivateLetterController.h"
#import "PrivateLetterContentController.h"
#import "PrivateLetterItem.h"
#import "AppDelegate.h"

@interface MessageRootController()

@property (retain, nonatomic) IBOutlet UIButton *composeButton;
@property (nonatomic) int curIndex;

- (IBAction)onClickTabButton:(id)sender;
- (IBAction)onClickComposeButton:(id)sender;

@end

@implementation MessageRootController

@synthesize composeButton = _composeButton;
@synthesize curIndex = _curIndex;

- (id)initWithNibName:(NSString *)nibNameOrNil bundle:(NSBundle *)nibBundleOrNil
{
    self = [super initWithNibName:nibNameOrNil bundle:nibBundleOrNil];
    if (self) {
        // Custom initialization
    
        MentionedMessageController* mentionedMsgController = [[MentionedMessageController alloc] initWithNibName:@"MentionedMessageController" bundle:nil];
        mentionedMsgController.homepageRootController = self;
     
        PrivateLetterController* privateLetterController = [[PrivateLetterController alloc] initWithNibName:@"PrivateLetterController" bundle:nil];
        privateLetterController.homepageRootController = self;
     
        _subTabControllers = [[NSArray alloc] initWithObjects:mentionedMsgController, privateLetterController, nil];
        
        [mentionedMsgController release];
        [privateLetterController release];
    }
    
    return self;
}

- (void)dealloc {
    
    [_subTabControllers release];
    
    [_composeButton release];
    [super dealloc];
}

- (void)didReceiveMemoryWarning
{
    // Releases the view if it doesn't have a superview.
    [super didReceiveMemoryWarning];
    
    // Release any cached data, images, etc that aren't in use.
}

#pragma mark - View lifecycle

// Implement loadView to create a view hierarchy programmatically, without using a nib.
- (void)loadView
{
    [super loadView];
    
    self.view.backgroundColor = [UIColor colorWithPatternImage:[UIImage imageNamed:@"all_bg"]];
    
    // Add the sub tab view
    UIView* controllerContainerView = [self.view viewWithTag:51];
    for (int i = 0; i < [_subTabControllers count]; i++) {
        UIViewController* subTabController = [_subTabControllers objectAtIndex:i];
        [controllerContainerView addSubview:subTabController.view];
    }
    
    // Set active view to "LatestInfo"
    [self setActiveSubTab:0];
}

- (void)viewWillAppear:(BOOL)animated {
    
    [super viewWillAppear:animated];
    
    UIViewController* viewController = [_subTabControllers objectAtIndex:self.curIndex];
    [viewController viewWillAppear:animated];
}

// Implement viewDidLoad to do additional setup after loading the view, typically from a nib.
- (void)viewDidLoad
{
    [super viewDidLoad];
}


- (void)viewDidUnload
{
    [self setComposeButton:nil];
    [super viewDidUnload];
    // Release any retained subviews of the main view.
    // e.g. self.myOutlet = nil;
}

- (BOOL)shouldAutorotateToInterfaceOrientation:(UIInterfaceOrientation)interfaceOrientation
{
    // Return YES for supported orientations
    return (interfaceOrientation == UIInterfaceOrientationPortrait);
}

#pragma mark - [ContactPickerDelegate]

- (void)contactPickerController:(ContactPickerController *)contactController userInfo:(UserInfo *)user {
    
    [contactController dismissModalViewControllerAnimated:YES];
    
    // User
    NSLog(@"User ID : %lld\nUser name : %@", user.userID, user.nickname);
    
    CollectionDataManager* sharedDataManager = [CollectionDataManager sharedInstance];
    NSDictionary* letterSet = sharedDataManager.privateLetterSet;
    long long userID = sharedDataManager.currentLoginUser.userID;
    NSArray* threads = [letterSet objectForKey:[NSString stringWithFormat:@"%lld", userID]];
    
    PrivateLetterThread* theThread = nil;
    for (PrivateLetterThread* oneThread in threads) {
        if (oneThread.objectID == user.userID) {
            theThread = oneThread;
            break;
        }
    }
    
    if (theThread == nil) {
        
    }
    
    PrivateLetterContentController* letterContentController = [[PrivateLetterContentController alloc] initWithNibName:@"PrivateLetterContentController" bundle:nil];
    letterContentController.conversationObjectUID = user.userID;//theThread.objectID;
    letterContentController.isEditMode = YES;
    
    AppDelegate* appDelegate = (AppDelegate*)[UIApplication sharedApplication].delegate;
    [appDelegate.rootNavigationController pushViewController:letterContentController animated:YES];
    [letterContentController release];
}

#pragma mark - Public methods

- (void)setActiveSubTab:(int)index {
    
    if (index < 0 || index >= [_subTabControllers count]) {
        return;
    }
    
    // Update the content view
    for (int i = 0; i < [_subTabControllers count]; i++) {
        UIViewController* subTabController = [_subTabControllers objectAtIndex:i];
        
        if (index == i) {
            subTabController.view.hidden = NO;
            if ([subTabController respondsToSelector:@selector(refresh)]) {
                [subTabController performSelector:@selector(refresh)];
            }
        }
        else {
            subTabController.view.hidden = YES;
        }
    }
    
    // Update the tab
    UIView* tabContainerView = [self.view viewWithTag:50];
    for (int i = 0; i < [_subTabControllers count]; i++) {
        int tag = i + 1;
        UIButton* button = (UIButton*)[tabContainerView viewWithTag:tag];
        if (button == nil) {
            continue;
        }
        
        button.selected = (i == index);
        self.composeButton.hidden = (1 != index);
    }
    
    self.curIndex = index;
}

#pragma mark - Private methods

- (IBAction)onClickTabButton:(id)sender {
    
    UIButton* button = (UIButton*)sender;
    uint index = button.tag - 1;
    if (index == NSNotFound) {
        return;
    }
    
    [self setActiveSubTab:index];
}

- (IBAction)onClickComposeButton:(id)sender {
    
    ContactPickerController* pickerController = [[ContactPickerController alloc] init];
    pickerController.delegate = self;
    AppDelegate* appDelegate = (AppDelegate*)[UIApplication sharedApplication].delegate;
    [appDelegate.rootNavigationController presentModalViewController:pickerController animated:YES];
    [pickerController release];
}

@end
